import { cookie } from '../../public/cookieFnNew.js';
import { ajax } from '../../public/promiseAjax.js'
import * as obj from '../public.js';
import { add } from './addCart.js';
const o = obj.default;
const goods = o.$('.goods')
const li = o.$$('.c_nav ul li')
const ul = o.$('.c_nav ul')
let idx = 0;
let first;
// console.log(shopCart)
// const shopCart = o.$('.icon-31gouwuche')
// shopCart.onclick = function () {
//   console.log(shopCart)
//   location.href = 'http://localhost:3000/html/shopcart.html'
// }
// 食品数据加载
ajax({
  url: 'http://10.11.55.120:3000/food',
}).then(res => {
  res = JSON.parse(res);
  new Page({
    data: res,
    number: 8,
    index: 0,
    cont: goods,
    pageCont: $('.page')
  })
});

class Page {
  constructor({ data = [], number = 8, index = 0, cont, pageCont }) {
    this.data = data
    this.number = number
    this.index = index
    this.cont = cont
    this.pageCont = pageCont

    this.render();
    this.pageRender()
    this.addEvent()
  }

  pageRender() {
    this.maxPage = Math.ceil(this.data.length / this.number)

    $('#pageIndex').innerHTML = this.index + 1
    $('#pageAll').innerHTML = this.maxPage
  }

  render() {
    let str = '';

    for (let i = this.index * this.number; i < (this.index + 1) * this.number; i++) {
      if (i < this.data.length) {
        const val = this.data[i]
        str += ` <div class="con_goods">
        <img src="${val.imgs}" alt="">
        <div class="s_name">¥ ${val.pricec} <i>${val.freeShipping}</i> <span>${val.buyers}人付款</span></div>
        <p>${val.name}</p>
        <div class="shop">${val.merchant}<em>${val.shippingPlace}</em></div>
        <input type="button" value="+" class="addCart"></input>
        </div>`
      }

    }
    this.cont.innerHTML = str
  }

  addEvent() {
    const that = this
    this.pageCont.onclick = function (eve) {
      const e = eve || window.event
      const target = e.target || e.srcElement
      if (target.id === 'prevBtn') {
        console.log(1);
        if (that.index === 0) {
          return
        } else {
          that.index -= 1
          that.pageRender()
        }
      }
      if (target.id === 'nextBtn') {
        console.log(111);
        if (that.index === that.maxPage - 1) {
          return
        } else {
          that.index += 1
          that.pageRender()
        }

      }
      that.render()
    }
  }
}
// goods.innerHTML = str
goods.onclick = function (eve) {
  const e = eve || window.event;
  const target = e.target || window.event;
  const li = o.$$('.addCart');
  const lis = [...li];
  let i = 0;
  lis.filter(val => val.index = i++)
  if (target.className === 'addCart') {
    const idx = target.index;
    const petCart = cookie.getCookie('petUserD');
    let userTel;
    let id;
    // 获取用户信息
    if (petCart) {
      petCart.split(',').forEach(val => {
        const a = val.split(':');
        if (a[0] === 'tel') {
          userTel = a[1]
        }
      })
    }
    ; (async () => {
      const obj = {};
      for (let t in data[idx]) {
        obj[t] = data[idx][t]
      }
      first = await ajax({
        url: 'http://10.11.55.120:3000/getUser',
        method: 'get',
        data: {
          userTel,
        },
      }).then(res => {
        return JSON.parse(res).data
      });

      console.log(first)
      if (first.length === 0 && !first[0]) {
        obj.num = 1;
        obj.check = true;
        first.push(obj)
        // 用户购物车没有数据，添加数据
        ajax({
          url: 'http://10.11.55.120:3000/userShopCart',
          method: 'post',
          data: {
            userTel,
            shopCart: `${JSON.stringify(first)}`
          },
        })
      } else {
        id = data[idx]._id;
        const falg = first.some((val) => {
          if (val._id === id) {
            val.num++
            ajax({
              url: 'http://10.11.55.120:3000/userShopCart',
              method: 'post',
              data: {
                userTel,
                shopCart: JSON.stringify(first)
              }
            })
          }
          return val._id === id
        })
        if (!falg) {
          obj.check = true;
          obj.num = 1;
          first.push(obj)
          // 用户购物车没有数据，添加数据
          ajax({
            url: 'http://10.11.55.120:3000/userShopCart',
            method: 'post',
            data: {
              userTel,
              shopCart: `${JSON.stringify(first)}`
            },
          })
        }
      }






    }
    )();
  }
}

// console.log(o.$$('.addCart'))
// goods.onclick = function (eve) {
//   const e = eve || window.event;
//   const target = e.target || window.event;
//   const li = o.$$('.addCart');
//   const lis = [...li];
//   let i = 0;
//   lis.filter(val => val.index = i++)
//   if (target.className === 'addCart') {
//     const idx = target.index;
//     const petCart = cookie.getCookie('petUserD');
//     let userTel;
//     let id;
//     // 获取用户信息
//     if (petCart) {
//       petCart.split(',').forEach(val => {
//         const a = val.split(':');
//         if (a[0] === 'tel') {
//           userTel = a[1]
//         }
//         // if(a[0] === 'uId'){
//         //   id = a[1]
//         // }
//       })
//     }
//     ; (async () => {
//       const obj = {};
//       for (let t in data[idx]) {
//         obj[t] = data[idx][t]
//       }
//       first = await ajax({
//         url: 'http://localhost:3000/getUser',
//         method: 'get',
//         data: {
//           userTel,
//           // shopCart: `[${JSON.stringify(obj)}]`
//         },
//       }).then(res => {
//         return JSON.parse(res).data
//       });
//       console.log(first)
//       if (first.length === 0 && !first[0]) {
//         obj.num = 1
//         first.push(obj)
//         // 用户购物车没有数据，添加数据
//         ajax({
//           url: 'http://localhost:3000/userShopCart',
//           method: 'post',
//           data: {
//             userTel,
//             shopCart: `${JSON.stringify(first)}`
//           },
//         })
//       } else {
//         id = data[idx]._id;
//         const falg = first.some((val) => {
//           if (val._id === id) {
//             val.num++
//             ajax({
//               url: 'http://localhost:3000/userShopCart',
//               method: 'post',
//               data: {
//                 userTel,
//                 shopCart: JSON.stringify(first)
//               }
//             })
//           }
//           return val._id === id
//         })
//         if (!falg) {
//           obj.num = 1;
//           first.push(obj)
//           // 用户购物车没有数据，添加数据
//           ajax({
//             url: 'http://localhost:3000/userShopCart',
//             method: 'post',
//             data: {
//               userTel,
//               shopCart: `${JSON.stringify(first)}`
//             },
//           })
//         }
//       }






//     }
//     )();
//   }
// }
// })



ul.onclick = function (eve) {
  const e = eve || window.event;
  const target = e.target || e.srcElement;
  const lis = Array.from(li)
  for (let i = 0; i < lis.length; i++) {
    lis[i].index = i
  }
  if (target.className !== 'cur' && target.tagName === 'LI') {
    lis[idx].className = '';
    lis[target.index].className = 'cur'
    idx = target.index;
    ajax({
      url: 'http://localhost:3000/' + lis[target.index].id,
    }).then(res => {
      res = JSON.parse(res);
      new Page({
        data: res,
        number: 8,
        index: 0,
        cont: goods,
        pageCont: $('.page')
      })
      // const data = res === '404' ? [] : JSON.parse(res);
    });
    class Page {
      constructor({ data = [], number = 8, index = 0, cont, pageCont }) {
        this.data = data
        this.number = number
        this.index = index
        this.cont = cont
        this.pageCont = pageCont
    
        this.render();
        this.pageRender()
        this.addEvent()
      }
      pageRender() {
        this.maxPage = Math.ceil(this.data.length / this.number)
    
        $('#pageIndex').innerHTML = this.index + 1
        $('#pageAll').innerHTML = this.maxPage
      }
      render() {
        let str = '';
    
        for (let i = this.index * this.number; i < (this.index + 1) * this.number; i++) {
          if (i < this.data.length) {
            const val = this.data[i]
            str += ` <div class="con_goods">
            <img src="${val.imgs}" alt="">
            <div class="s_name">¥ ${val.pricec} <i>${val.freeShipping}</i> <span>${val.buyers}人付款</span></div>
            <p>${val.name}</p>
            <div class="shop">${val.merchant}<em>${val.shippingPlace}</em></div>
            <input type="button" value="+" class="addCart"></input>
            </div>`
          }
    
        }
        this.cont.innerHTML = str
      }
      addEvent() {
        const that = this
        this.pageCont.onclick = function (eve) {
          const e = eve || window.event
          const target = e.target || e.srcElement
          if (target.id === 'prevBtn') {
            console.log(1);
            if (that.index === 0) {
              return
            } else {
              that.index -= 1
              that.pageRender()
            }
          }
          if (target.id === 'nextBtn') {
            console.log(111);
            if (that.index === that.maxPage - 1) {
              return
            } else {
              that.index += 1
              that.pageRender()
            }
    
          }
          that.render()
        }
      }
    }
    goods.onclick = function (eve) {
      const e = eve || window.event;
      const target = e.target || window.event;
      const li = o.$$('.addCart');
      const lis = [...li];
      let i = 0;
      lis.filter(val => val.index = i++)
      if (target.className === 'addCart') {
        const idx = target.index;
        const petCart = cookie.getCookie('petUserD');
        let userTel;
        let id;
        // 获取用户信息
        if (petCart) {
          petCart.split(',').forEach(val => {
            const a = val.split(':');
            if (a[0] === 'tel') {
              userTel = a[1]
            }
          })
        }
        ; (async () => {
          const obj = {};
          for (let t in data[idx]) {
            obj[t] = data[idx][t]
          }
          console.log(obj)
          first = await ajax({
            url: 'http://localhost:3000/getUser',
            method: 'get',
            data: {
              userTel,
              // shopCart: `[${JSON.stringify(obj)}]`
            },
          }).then(res => {
            return JSON.parse(res).data
          });
          console.log(first)
          if (first.length === 0 && !first[0]) {
            obj.num = 1;
            obj.check = true;
            first.push(obj)
            // 用户购物车没有数据，添加数据
            ajax({
              url: 'http://localhost:3000/userShopCart',
              method: 'post',
              data: {
                userTel,
                shopCart: `${JSON.stringify(first)}`
              },
            })
          } else {
            id = data[idx]._id;
            const falg = first.some((val) => {
              if (val._id === id) {
                val.num++
                ajax({
                  url: 'http://localhost:3000/userShopCart',
                  method: 'post',
                  data: {
                    userTel,
                    shopCart: JSON.stringify(first)
                  }
                })
              }
              return val._id === id
            })
            if (!falg) {
              obj.num = 1;
              obj.check = true;
              first.push(obj)
              // 用户购物车没有数据，添加数据
              ajax({
                url: 'http://localhost:3000/userShopCart',
                method: 'post',
                data: {
                  userTel,
                  shopCart: `${JSON.stringify(first)}`
                },
              })
            }
          }
        }
        )();
      }
    }
  } else {
    goods.innerHTML = str
    goods.onclick = function (eve) {
      const e = eve || window.event;
      const target = e.target || window.event;
      const li = o.$$('.addCart');
      const lis = [...li];
      let i = 0;
      lis.filter(val => val.index = i++)
      if (target.className === 'addCart') {
        const idx = target.index;
        const petCart = cookie.getCookie('petUserD');
        let userTel;
        let id;
        // 获取用户信息
        if (petCart) {
          petCart.split(',').forEach(val => {
            const a = val.split(':');
            if (a[0] === 'tel') {
              userTel = a[1]
            }
            // if(a[0] === 'uId'){
            //   id = a[1]
            // }
          })
        }
        ; (async () => {
          const obj = {};
          for (let t in data[idx]) {
            obj[t] = data[idx][t]
          }
          first = await ajax({
            url: 'http://localhost:3000/getUser',
            method: 'get',
            data: {
              userTel,
              // shopCart: `[${JSON.stringify(obj)}]`
            },
          }).then(res => {
            return JSON.parse(res).data
          });
          console.log(first)
          if (first.length === 0 && !first[0]) {
            obj.num = 1
            first.push(obj)
            // 用户购物车没有数据，添加数据
            ajax({
              url: 'http://localhost:3000/userShopCart',
              method: 'post',
              data: {
                userTel,
                shopCart: `${JSON.stringify(first)}`
              },
            })
          } else {
            id = data[idx]._id;
            const falg = first.some((val) => {
              if (val._id === id) {
                val.num++
                ajax({
                  url: 'http://localhost:3000/userShopCart',
                  method: 'post',
                  data: {
                    userTel,
                    shopCart: JSON.stringify(first)
                  }
                })
              }
              return val._id === id
            })
            if (!falg) {
              obj.num = 1;
              first.push(obj)
              // 用户购物车没有数据，添加数据
              ajax({
                url: 'http://localhost:3000/userShopCart',
                method: 'post',
                data: {
                  userTel,
                  shopCart: `${JSON.stringify(first)}`
                },
              })
            }
          }
        }
        )();
      }
    }
  }
}




// // 定义每页显示的商品数量和当前页码
// const perPage = 8; // 每页显示的商品数量
// let currentPage = 1; // 当前页码


// // 根据当前页码和每页显示的数量截取对应的商品数据
// const startIndex = (currentPage - 1) * perPage;
// const endIndex = startIndex + perPage;
// const displayedProducts = goods.slice(startIndex, endIndex);


// $(prevBtn).addEventListener('click', previousPage); // 上一页按钮点击事件
// $(nextBtn).addEventListener('click', nextPage); // 下一页按钮点击事件

// function previousPage() {
//   if (currentPage > 1) {
//     currentPage--; // 更新当前页码
//     renderData(); // 重新渲染商品列表
//   }
// }

// function nextPage() {
//   const totalPages = Math.ceil(products.length / perPage); // 计算总页数
//   if (currentPage < totalPages) {
//     currentPage++; // 更新当前页码
//     renderData(); // 重新渲染商品列表
//   }
// }

// function renderData() {
//   const startIndex = (currentPage - 1) * perPage; // 计算起始索引
//   const endIndex = startIndex + perPage; // 计算结束索引
//   const displayedProducts = products.slice(startIndex, endIndex); // 截取对应的商品数据

//   goods.innerHTML = ''; // 清空容器

//   displayedProducts.forEach(product => {
//     const productElement = document.createElement('div');
//     productElement.textContent = product.name;
//     productListContainer.appendChild(productElement);
//   });
// }

function $(m) {
  return document.querySelector(m)
}